/**
 * Copyright (C) 2011 Audit Logger Project. All rights reserved.
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package org.auditlogger.security;

import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.auditlogger.config.ConfigurationServices;
import org.auditlogger.config.spi.PropertiesConfigurator;
import org.auditlogger.util.Base64EncoderDecoder;

/**
 * This class performs encryption and decryption for each log record.
 * 
 * @author <a href="mailto:ravi.sharda@gmail.com">Ravi Sharda</a>
 */
abstract class EncryptorDecryptor {
	
	private static final Log logger = LogFactory.getLog(EncryptorDecryptor.class);
	
	// It's enough to instantiate a provider once and for all.
	private static PropertiesConfigurator config = 
		ConfigurationServices.getPropertiesConfigurator();
	
	private SecretKeySpec secretKeySpec = null;
	private Cipher cipher = null;
	
	/**
	 * Provides easy means for subtypes to get an instantiated configurator. 
	 *  
	 * @return PropertiesConfigurator
	 */
	protected PropertiesConfigurator getConfigurator() {
		return config;
	}
	
	EncryptorDecryptor() {
	}
	
	/**
	 * Get an instance of  
	 * 
	 * @return
	 * @exception 
	 */
	static EncryptorDecryptor getInstance() {
		EncryptorDecryptor encryptor = null;
		if (config.getEncryptionAlgorithm().equalsIgnoreCase("Blowfish")) {
			
			// TODO: A singleton ould suffice
			encryptor = new BlowfishEncryptorDecryptor();
		} else {
			throw new ExceptionInInitializerError("Missing or invalid encryption algorithm");
		}
		return encryptor;
	}
	
	/**
	 * A template method for initialization. 
	 */
	public void initialize () {
		secretKeySpec = prepareSecretKeySpec();
		cipher = prepareCipher();
	}
	
	protected abstract SecretKeySpec prepareSecretKeySpec();
	
	protected abstract Cipher prepareCipher() throws EncryptionException;
	
	public String encrypt(String plainText) throws EncryptionException {
		this.initialize();
		try {
			cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
			 byte[]encryptedData = cipher.doFinal(plainText.getBytes(
						config.defaultEncoding()));
			logger.debug("encryptedData: " + new String(encryptedData).intern());
			return Base64EncoderDecoder.encodeForBase64(encryptedData);
		} catch (UnsupportedEncodingException e) {
			throw new EncryptionException(e);
		} catch (InvalidKeyException e) {
			throw new EncryptionException(e);
		} catch (IllegalBlockSizeException e) {
			throw new EncryptionException(e);
		} catch (BadPaddingException e) {
			throw new EncryptionException(e);
		}
	}
	
	/**
	 * Decrypt the cipher text.
	 * 
	 * @param encodedCipherText BAse64 encoded cipher text
	 * @return Decrypted text.
	 * 
	 */
	public String decrypt(String encodedCipherText) {
		this.initialize();
		try {
			byte[] cipherText = Base64EncoderDecoder.decodeFromBase64(encodedCipherText);
			logger.debug("Decoded cipherText: " + new String(cipherText).intern());
			
			cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
			byte[] decryptedData = cipher.doFinal(cipherText);
			return new String(decryptedData, "UTF-8");
			
		} catch (Exception  e) {
			throw new EncryptionException(e);
		} 
	}

}
